var express = require('express');
var router = express.Router();
var fs = require("fs");

// 配置上传图片
var multer = require("multer");
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if(file.fieldname=="tea"){
        cb(null, './public/images/classify')
    }else{
      cb(null, './public/images/goods')
    }
    
  },
  filename: function (req, file, cb) {
    if(!req.goodsImg){
      req.goodsImg = [];
    }
    if(!req.pic){
      req.pic = [];
    }
    var suffix = file.mimetype.split("/")[1];
    var fieldname = file.fieldname + '-' + Date.now()+"."+suffix;
    cb(null, fieldname);
    if(file.fieldname=="tea"){
      req.classifyImg ="/images/classify/"+fieldname;
    }else if(file.fieldname=="goods"){
      req.goodsImg.push("/images/goods/"+fieldname);
    }else{
      req.pic.push("/images/goods/"+fieldname);
    }
  }
})
var upload = multer({ storage: storage })

var hotDAO = require("../bin/db/hotDAO.js");
var classifyDAO = require("../bin/db/classifyDAO.js");
var screenDAO = require("../bin/db/screenDAO.js");
var goodsDAO = require("../bin/db/goodsDAO.js");
var cartDAO = require("../bin/db/cartDAO.js");
var isLogin = require("../bin/isLogin.js");

// 热门茶销的接口
router.get("/hotimg",(req,res)=>{
  hotDAO.find()
  .then(data=>{
    res.json({err:0,data});
  })
});

// 添加分类的接口
router.post("/addclassify",upload.single("tea"),(req,res)=>{
  classifyDAO.findOne({classifyName:req.body.classifyName})
  .then(data=>{
   
    var tea = {
      img : req.classifyImg,
      teaName:req.body.teaName,
    }
    if(data){
      var isHas = false;
      data.tea.forEach(function(e) {
        if(e.teaName==req.body.teaName)return isHas = true;
      }, this);
      if(!isHas){
          data.tea.push(tea);
          data.save()
          .then(data=>{
            res.json({err:0,msg:"添加茶名成功！"});
          })
      }else{
        fs.unlinkSync("./public/"+req.classifyImg)
        res.json({err:0,msg:"不能重复添加茶名！"});
        
      }
    }else{
      var c = new classifyDAO({classifyName:req.body.classifyName,});
      c.tea.push(tea);
      c.save()
      .then(data=>{
        res.json({err:0,msg:"添加新分类成功！"});
      })
    }

  })
});

// 全部产品分类的接口
router.get("/classify",(req,res)=>{
  classifyDAO.find()
  .then(data=>{
    res.json({err:0,data});
  })
});

// 筛选商品的接口
router.get("/filter",(req,res)=>{
  screenDAO.find()
  .then(data=>{
    // console.log(data);
    res.json({err:0,data});
  })
});

// 添加商品的接口
router.post("/addshopping",upload.fields([{name:"goods"},{name:"pic"}]),(req,res)=>{
  var g = new goodsDAO({
    goodsName:req.body.goodsName,
    description:req.body.description,
    price:req.body.price,
    classifyName:req.body.classify.split(",")[0],
    teaName:req.body.classify.split(",")[1],
    netContent:req.body.netContent,
    goodsClass:req.body.goodsClass,
    use:req.body.use,
    year:req.body.year,
    odor:req.body.odor,
    season:req.body.season,
    storage:req.body.storage,
    goodsImg:req.goodsImg,
    goodsDescriptionImg:req.pic,
  });
  g.save()
  .then(data=>{
      req.goodsImg = null;
      req.pic = null;
      res.json({err:0,msg:"添加商品成功！"});
  });
  
});

// 商品列表接口
router.get("/goodslist",(req,res)=>{
  // console.log(req.query)
  var sort = {}
  if(!req.query.screen){
    sort.classifyName = req.query.classifyName;
    sort.teaName = req.query.teaName;
  }else{
    sort.classifyName = req.query.classifyName;
    sort.teaName = req.query.teaName;
    var screen = JSON.parse(req.query.screen);
    if(screen.goodsClass){
      sort.goodsClass = screen.goodsClass;
    }
    if(screen.use){
      sort.use = screen.use;
    }
    if(screen.season){
      sort.season = screen.season;
    }
    if(screen.year){
      sort.year = screen.year;
    }
    if(screen.netContent.min){
      sort.netContent = {$gt:screen.netContent.min}
    }
    if(screen.netContent.max){
      sort.netContent = {$lt:screen.netContent.max}
    }
  }
  if(req.query.priceSort){
    var  params = {price:req.query.priceSort}
  }else{
    if(req.query._id){
      var params = {_id:-1}
    }else{
      var params = {_id:1}
    }
  }
  // console.log(sort);
  goodsDAO.find(sort,{use:0,storage:0,goodsDescriptionImg:0})
  .sort(params)
  .then(data=>{
    res.json({err:0,data});
  });
});

// 商品详情页的接口
router.get("/product",(req,res)=>{
  goodsDAO.findOne(req.query)
  .then(data=>{
    res.json({err:0,data});
  });
});

// 加入购物车的接口
router.post("/addshoppingcart",isLogin);
router.post("/addshoppingcart",(req,res)=>{
  cartDAO.findOne({user:req.session.user._id,goods:req.body._id})
  .then(data=>{
    if(!data){
      var c =new cartDAO({
        user:req.session.user._id,
        goods:req.body._id,
        count:req.body.count
      });
      c.save()
      .then(()=>{
        res.json({err:0,msg:"添加购物车成功！"});
      })
    }else{
      res.json({err:0,msg:"这件商品你已经添加过购物车了！"});
    }
  })
});

// 购物车页面请求
router.get("/shoppingcart",isLogin);
router.get("/shoppingcart",(req,res)=>{
  cartDAO.find({user:req.session.user._id})
  .populate("goods",{_id:1,goodsName:1,price:1,goodsImg:1})
  .then(data=>{
    res.json({err:0,data});
  });
});

// 购物车数量增加、减少的请求
router.post("/count",(req,res)=>{
  cartDAO.findOne({user:req.session.user._id,goods:req.body._id})
  .then(data=>{
    if(req.body.change){
      data.count++;
      data.save()
      .then(data=>{
        res.json({err:0,msg:"数量+1"});
      })
    }else{
      if(data.count<=1){
        res.json({err:0,msg:"数量不减"});
      }else{
        data.count--;
        data.save()
        .then(data=>{
          res.json({err:0,msg:"数量-1"});
        })
      }
    }
  });
});

// 删除购物车商品的接口
router.get("/removeshoppingcart",isLogin);
router.get("/removeshoppingcart",(req,res)=>{
  var id = [];
  req.query.checkId.map((e)=>{
    var arr = {};
    arr._id = e;
    id.push(arr);
  })
  
  cartDAO.remove({$or:id})
  .then(()=>{
    res.json({err:0,msg:"删除商品成功"});
  })
  
});

module.exports = router;
